const fs = require('fs');
const path = require('path');

class Logger {
    constructor() {
        this.logDir = path.join(__dirname, '../../logs');
        this.ensureLogDirectory();
    }

    ensureLogDirectory() {
        if (!fs.existsSync(this.logDir)) {
            fs.mkdirSync(this.logDir);
        }
    }

    formatMessage(level, message, data = null) {
        const timestamp = new Date().toISOString();
        const logData = {
            timestamp,
            level,
            message,
            ...(data && { data })
        };
        return JSON.stringify(logData);
    }

    writeLog(level, message, data = null) {
        const date = new Date().toISOString().split('T')[0];
        const logFile = path.join(this.logDir, `${date}.log`);
        const logEntry = this.formatMessage(level, message, data) + '\n';

        fs.appendFileSync(logFile, logEntry);

        // 同时输出到控制台
        if (process.env.NODE_ENV !== 'production') {
            console.log(logEntry);
        }
    }

    info(message, data = null) {
        this.writeLog('INFO', message, data);
    }

    error(message, data = null) {
        this.writeLog('ERROR', message, data);
    }

    warn(message, data = null) {
        this.writeLog('WARN', message, data);
    }

    debug(message, data = null) {
        if (process.env.NODE_ENV !== 'production') {
            this.writeLog('DEBUG', message, data);
        }
    }

    // 记录用户操作
    logUserAction(userId, action, details = null) {
        this.info(`User ${userId} performed ${action}`, details);
    }

    // 记录系统事件
    logSystemEvent(event, details = null) {
        this.info(`System event: ${event}`, details);
    }

    // 记录错误
    logError(error, context = null) {
        this.error(error.message, {
            stack: error.stack,
            context
        });
    }
}

module.exports = new Logger();